import utils from '@/utils/index.js'

import API from './api.js'

// 地理信息类，包含天气
class Location {
  constructor () {
    // 初始化
    this.country = ''
    this.province = ''
    this.city = ''
    this.district = ''
    this.address = '未知地区'
  }
  
  // 获取默认位置
  defaultLocate () {
    this.type = 'default'
    this.country = '中国'
    this.province = '北京市'
    this.city = ''
    this.district = ''
    this.address = this.province + this.city + this.district
    this.lon = 116.407526
    this.lat = 39.904030
    this.adcode = '110000'
    this.utc = 8
  }
  
  // 手动指定位置信息
  setLocate (options) {
    this.type = 'set'
    if (!utils.obj.isObject(options)|| !utils.obj.isNumber(options.lon) || !utils.obj.isNumber(options.lat)) {
      return
    }
    
    this.country = typeof options.country === 'string' && options.country !== '' ? options.country : '中国'
    this.province = typeof options.province === 'string' ? options.province : ''
    this.city = typeof options.city === 'string' ? options.city : ''
    this.district = typeof options.district === 'string' ? options.district : ''
    this.address = this.province + this.city + this.district
    this.utc = utils.obj.isNumber(options.utc) ? options.utc : 8
    this.adcode = typeof options.district === 'string' ? options.adcode : ''
  }
  
  // 调用定位能力获取当前位置
  async locate () {
    this.type = 'gps'
    
    // 定位获取UTC暂只支持通过系统的JS时间方法获取
    this.utc = new Date().getTimezoneOffset() / 60 * (-1)
    
    const loc = await Location.getPos()
    // 初始化
    this.lon = loc.lon
    this.lat = loc.lat
    
    // 先进行逆地理编码
    const regeoData = await Location.req('regeo', {
      location: `${loc.lon},${loc.lat}`
    })
    // 获取地址信息
    this.country = regeoData.regeocode.addressComponent.country
    this.province = regeoData.regeocode.addressComponent.province
    this.city = regeoData.regeocode.addressComponent.city
    this.district = regeoData.regeocode.addressComponent.district
    this.address = this.province + this.city + this.district
    if (this.address === '') {
      this.address = '未知地区'
      return
    }
    
    // 再进行地理编码
    const geoData = await Location.req('geo', {
      address: this.address
    })
    // 获取地理信息
    if (!geoData.geocodes || geoData.geocodes.length <= 0) {
      // 没有查到地理信息
      return
    }
    // 根据地理信息更新经纬度
    const locationArr = geoData.geocodes[0].location.split(',')
    this.lon = parseFloat(locationArr[0])
    this.lat = parseFloat(locationArr[1])
    // 获取区域码
    this.adcode = geoData.geocodes[0].adcode
  }
  
  // 获取天气
  async getWeather () {
    if (this.isEnabled()) {
      if (this.weathers) {
        return this.weathers
      }
      
      const weatherData = await Location.req('weather', {
        city: this.adcode,
        extensions: 'all'
      })
      if (!weatherData.forecasts || weatherData.forecasts.length <= 0) {
        return
      }
      this.weathers = weatherData.forecasts[0].casts
      this.solveWeathers()
      return this.weathers
    }
  }
  
  // 修改天气描述
  solveWeathers () {
    
  }
  
  // 调用系统能力进行定位
  static getPos () {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'wgs84',
        success: (res) => {
          const result = {
            lon: res.longitude,
            lat: res.latitude
          }
          resolve(result)
        },
        fail: (e) => {
          reject(utils.err('LOCATE_ERROR', e))
        },
        
      })       
    })
  }
  
  // 请求接口
  static req (key, data) {
    return new Promise((resolve, reject) => {
      // 加入用户key字段
      data.key = API.userKey
      
      const apiObj = API[key]
      if (apiObj.method === 'POST') {
        utils.req.post(apiObj.path, data).then((res) => {
          if (res.status == 0) {
            reject(utils.err('LOCATE_API_ERROR'))
          }
          else {
            resolve(res)
          }
        })
        .catch((e) => {
          reject(e)
        })
      }
      else {
        utils.req.get(apiObj.path, data).then((res) => {
          if (res.status == 0) {
            reject(utils.err('LOCATE_API_ERROR'))
          }
          else {
            resolve(res)
          }
        })
        .catch((e) => {
          reject(e)
        })
      }
    })
  }
  
  /* @section get方法 */
  // 判断地址是否有效
  isEnabled () {
    return utils.obj.isNumber(this.lon) && utils.obj.isNumber(this.lat)
  }
  
  // 获取最简地址
  getSimAddress () {
    this.province + this.city + this.district
    if (this.district !== '') {
      return this.district
    }
    if (this.city !== '') {
      return this.city
    }
    if (this.province !== '') {
      return this.province
    }
    if (this.country !== '') {
      return this.country
    }
    return this.address
  }
}

export default Location